/**
 * Project Name:zyhj-web
 * File Name:LpglServiceImpl.java
 * Package Name:com.vviton.zyhj.consumer.service.impl
 * Date:2016年11月14日下午6:31:12
 *
 */

package com.vviton.zyhj.admin.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.vviton.zyhj.admin.service.LpglService;
import com.vviton.zyhj.common.base.AppConfig;
import com.vviton.zyhj.common.base.BaseService;
import com.vviton.zyhj.common.common.CodeConstants;
import com.vviton.zyhj.common.common.CommonConstants;
import com.vviton.zyhj.common.common.ValidatorConstants;
import com.vviton.zyhj.common.dao.TYyxtHzglHzgxbMapper;
import com.vviton.zyhj.common.dao.TYyxtLpglLpxxMapper;
import com.vviton.zyhj.common.dao.TYyxtLpglLpyfjdygxMapper;
import com.vviton.zyhj.common.entity.TYyxtHzglHzgxb;
import com.vviton.zyhj.common.entity.TYyxtLpglLpxx;
import com.vviton.zyhj.common.entity.TYyxtLpglLpyfjdygx;
import com.vviton.zyhj.common.utils.ErrorBean;
import com.vviton.zyhj.common.utils.FileBean;
import com.vviton.zyhj.common.utils.FileUtils;
import com.vviton.zyhj.common.utils.ResultJson;
import com.vviton.zyhj.common.utils.page.Page;
import com.vviton.zyhj.common.view.ParamLpcx;
import com.vviton.zyhj.common.view.ParamLpxx;
import com.vviton.zyhj.common.view.ParamLpxxZt;
import com.vviton.zyhj.common.view.ViewLpcx;
import com.vviton.zyhj.common.view.ViewLpxx;

/**
 * ClassName:LpglServiceImpl <br/>
 * Function: 礼品管理Service. <br/>
 * Date: 2016年11月14日 下午6:31:12 <br/>
 *
 * @author huangqq
 * @version 1.0
 * @since JDK 1.7
 */
public class LpglServiceImpl extends BaseService implements LpglService {

    /** 日志 */
    private static Logger logger = Logger.getLogger(LpglServiceImpl.class);

    /** appConfig */
    @Autowired
    private AppConfig appConfig;

    /** 礼品信息Mapper */
    @Autowired
    private TYyxtLpglLpxxMapper tYyxtLpglLpxxMapper;

    /** 礼品与附件信息Mapper */
    @Autowired
    private TYyxtLpglLpyfjdygxMapper lpyfjdygxMapper;

    /** 长度常量 */
    private static final long MAX_LENGTH50 = 50;

    /** 长度常量 */
    private static final long MAX_LENGTH300 = 80;

    /** 合作关系表 */
    @Autowired
    private TYyxtHzglHzgxbMapper tYyxtHzglHzgxbMapper;

    /**
     * insertLpxx,插入礼品信息（添加礼品）. <br/>
     * Author: huangqq <br/>
     * Create Date: 2016年11月15日 <br/>
     * ===============================================================<br/>
     * Modifier: huangqq <br/>
     * Modify Date: 2016年11月15日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param paramLpxx 礼品信息
     * @return 执行结果
     * @since JDK 1.7
     */
    @Override
    public ResultJson insertLpxx(ParamLpxx paramLpxx) {
        logger.info("插入礼品信息开始");
        ResultJson resultJson = new ResultJson(false);
        List<ErrorBean> errCodeList = validateLpxx(paramLpxx);
        if (CollectionUtils.isNotEmpty(errCodeList)) {
            resultJson.setErrorList(errCodeList);
            return resultJson;
        }
        logger.info("校验结束");

        String opCode = paramLpxx.getOperatercode();
        TYyxtLpglLpxx lpglLpxx = new TYyxtLpglLpxx();
        CommonConstants.copyProperties(lpglLpxx, paramLpxx);
        lpglLpxx.setId(this.getKey());
        lpglLpxx.setOperatetime(new Date());
        lpglLpxx.setCreatercode(opCode);
        lpglLpxx.setCreatertime(new Date());
        lpglLpxx.setDelflag(CommonConstants.DELFLAG_ADD);
        lpglLpxx.setVersions(this.getVersion());
        lpglLpxx.setZkzt(CodeConstants.ZKZT_ZK);
        lpglLpxx.setDhsl(0);
        lpglLpxx.setTgfmc(appConfig.getAdminMc());
        lpglLpxx.setTgfzh(appConfig.getAdminZh());

        String ywy = lpglLpxx.getYwy();

        if (StringUtils.isNotBlank(paramLpxx.getTgflx())) {
            if (CodeConstants.TGFLX_HZF.equals(paramLpxx.getTgflx())) {
                TYyxtHzglHzgxb tYyxtHzglHzgxb = tYyxtHzglHzgxbMapper.getHzgxbxxByZh(opCode, ywy, CodeConstants.XYZT_YSH);
                if (tYyxtHzglHzgxb != null) {
                    lpglLpxx.setHzfid(tYyxtHzglHzgxb.getHzfid());
                }
            } else if (CodeConstants.TGFLX_PT.equals(paramLpxx.getTgflx())) {
                lpglLpxx.setHzfid(appConfig.getAdminKtId());
            }

        }

        int cnt = tYyxtLpglLpxxMapper.insertLpxx(lpglLpxx);

        List<TYyxtLpglLpyfjdygx> lpsltList = paramLpxx.getLpsltList();
        String lpid = lpglLpxx.getId();
        if (CollectionUtils.isNotEmpty(lpsltList)) {
            for (TYyxtLpglLpyfjdygx lpyfjdygx : lpsltList) {
                lpyfjdygx.setId(this.getKey());
                lpyfjdygx.setOperatercode(opCode);
                lpyfjdygx.setOperatetime(new Date());
                lpyfjdygx.setCreatertime(new Date());
                lpyfjdygx.setCreatercode(opCode);
                lpyfjdygx.setDelflag(CommonConstants.DELFLAG_ADD);
                lpyfjdygx.setVersions(this.getVersion());
                lpyfjdygx.setLpid(lpid);
                lpyfjdygx.setYwy(ywy);
                lpyfjdygx.setMtlx(FileUtils.distFileType(lpyfjdygx.getLjm()));
                lpyfjdygxMapper.insertLpyfjdygx(lpyfjdygx);
            }
        }
        logger.info("插入礼品信息结束");
        if (cnt > 0) {
            resultJson.setResult(true);
            resultJson.setObject(lpid);
        }
        return resultJson;
    }

    /**
     * updateLpxx,更新礼品信息. <br/>
     * Author: huangqq <br/>
     * Create Date: 2016年11月15日 <br/>
     * ===============================================================<br/>
     * Modifier: huangqq <br/>
     * Modify Date: 2016年11月15日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param paramLpxx 礼品信息
     * @return 礼品信息
     * @since JDK 1.7
     */
    @Override
    public ResultJson updateLpxx(ParamLpxx paramLpxx) {
        logger.info("更新礼品信息开始");
        ResultJson resultJson = new ResultJson(false);
        List<ErrorBean> errCodeList = new ArrayList<ErrorBean>();
        String lpid = paramLpxx.getId();
        if (StringUtils.isBlank(lpid)) {
            resultJson.setMessage(ValidatorConstants.E1000);
            return resultJson;
        }
        errCodeList = validateLpxx(paramLpxx);
        if (CollectionUtils.isNotEmpty(errCodeList)) {
            resultJson.setErrorList(errCodeList);
            return resultJson;
        }
        logger.info("校验结束");

        logger.info("更新礼品信息");
        TYyxtLpglLpxx lpglLpxx = new TYyxtLpglLpxx();
        CommonConstants.copyProperties(lpglLpxx, paramLpxx);
        lpglLpxx.setVersions(this.getVersion());
        lpglLpxx.setOperatetime(new Date());
        lpglLpxx.setDelflag(CommonConstants.DELFLAG_UPDATE);
        int cnt = tYyxtLpglLpxxMapper.updateLpxx(lpglLpxx);

        String ywy = lpglLpxx.getYwy();

        String opCode = paramLpxx.getOperatercode();

        //删除附件 对应关系，重新插入数据
        logger.info("删除附件 对应关系，重新插入数据");
        List<TYyxtLpglLpyfjdygx> lpyfjdygxList = lpyfjdygxMapper.getLpyfjdygxBylpid(lpid, ywy);
        if (CollectionUtils.isNotEmpty(lpyfjdygxList)) {
            for (TYyxtLpglLpyfjdygx lpyfjdygx : lpyfjdygxList) {
                lpyfjdygx.setOperatercode(opCode);
                lpyfjdygx.setOperatetime(new Date());
                lpyfjdygx.setDelflag(CommonConstants.DELFLAG_DELETE);
                lpyfjdygx.setVersions(this.getVersion());
                lpyfjdygxMapper.deleteLpfjdygxById(lpyfjdygx);
            }
        }
        //重新插入数据
        logger.info("重新插入数据");
        List<TYyxtLpglLpyfjdygx> lpsltList = paramLpxx.getLpsltList();
        if (CollectionUtils.isNotEmpty(lpsltList)) {
            for (TYyxtLpglLpyfjdygx lpyfjdygx : lpsltList) {
                lpyfjdygx.setId(this.getKey());
                lpyfjdygx.setOperatercode(opCode);
                lpyfjdygx.setOperatetime(new Date());
                lpyfjdygx.setCreatertime(new Date());
                lpyfjdygx.setCreatercode(opCode);
                lpyfjdygx.setDelflag(CommonConstants.DELFLAG_ADD);
                lpyfjdygx.setVersions(this.getVersion());
                lpyfjdygx.setLpid(lpid);
                lpyfjdygx.setYwy(ywy);
                lpyfjdygx.setMtlx(FileUtils.distFileType(lpyfjdygx.getLjm()));
                lpyfjdygxMapper.insertLpyfjdygx(lpyfjdygx);
            }
        }
        logger.info("插入礼品对应关系结束");

        if (cnt > 0) {
            resultJson.setResult(true);
        }
        return resultJson;
    }

    /**
     * validateLpxx,校验礼品信息. <br/>
     * Author: huangqq <br/>
     * Create Date: 2016年11月15日 <br/>
     * ===============================================================<br/>
     * Modifier: huangqq <br/>
     * Modify Date: 2016年11月15日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param paramLpxx 礼品信息
     * @return 错误信息集合
     * @since JDK 1.7
     */
    private List<ErrorBean> validateLpxx(ParamLpxx paramLpxx) {
        List<ErrorBean> errCodeList = new ArrayList<ErrorBean>();
        ErrorBean errorBean = null;
        logger.info("------------礼品名称校验-------------");
        String lpmc = paramLpxx.getLpmc();
        if (StringUtils.isBlank(lpmc)) {
            errorBean = new ErrorBean();
            errorBean.setErrorData(ValidatorConstants.E1001);
            errCodeList.add(errorBean);
        } else {
            paramLpxx.setLpmc(lpmc.trim());
            if (lpmc.trim().length() > MAX_LENGTH50) {
                errorBean = new ErrorBean();
                errorBean.setErrorData(ValidatorConstants.E1002);
                errCodeList.add(errorBean);
            }
        }
        logger.info("-----------礼品简介校验--------------");
        String lpjj = paramLpxx.getLmpj();
        if (StringUtils.isNotBlank(lpjj)) {
            paramLpxx.setLmpj(lpjj.trim());
            if (lpjj.trim().length() > MAX_LENGTH300) {
                errorBean = new ErrorBean();
                errorBean.setErrorData(ValidatorConstants.E1003);
                errCodeList.add(errorBean);
            }
        }
        logger.info("------------礼品类目校验-------------");
        if (StringUtils.isBlank(paramLpxx.getLplmid())) {
            errorBean = new ErrorBean();
            errorBean.setErrorData(ValidatorConstants.E1004);
            errCodeList.add(errorBean);
        }
        logger.info("------------礼品业务域校验-------------");
        if (StringUtils.isBlank(paramLpxx.getYwy())) {
            errorBean = new ErrorBean();
            errorBean.setErrorData(ValidatorConstants.E1005);
            errCodeList.add(errorBean);
        }
        logger.info("--------------礼品业务域校验--------------");
        if (errCodeList.size() > 0) {
            return errCodeList;
        }
        logger.info("--------------礼品logo校验--------------");
        TYyxtLpglLpyfjdygx logo = paramLpxx.getLpLogo();
        if (logo == null) {
            errorBean = new ErrorBean();
            errorBean.setErrorData(ValidatorConstants.E1006);
            errCodeList.add(errorBean);
        } else {
            logo.setFjfl(CodeConstants.FJFL_LPLOGO);
            logo.setSfxyzh(CodeConstants.YESORNO_NO);
            if (StringUtils.isBlank(logo.getWjgs()) || StringUtils.isBlank(logo.getFjdz()) || logo.getFjdx() == null || StringUtils.isBlank(logo.getLjm())) {
                errorBean = new ErrorBean();
                errorBean.setErrorData(ValidatorConstants.E1007);
                errCodeList.add(errorBean);
            }
        }
        List<TYyxtLpglLpyfjdygx> lpsltList = paramLpxx.getLpsltList();
        logger.info("--------------礼品缩略图校验--------------");
        if (CollectionUtils.isEmpty(lpsltList)) {
            errorBean = new ErrorBean();
            errorBean.setErrorData(ValidatorConstants.E1008);
            errCodeList.add(errorBean);
        } else {
            for (TYyxtLpglLpyfjdygx lpyfjdygx : lpsltList) {
                lpyfjdygx.setFjfl(CodeConstants.FJFL_SLT);
                lpyfjdygx.setSfxyzh(CodeConstants.YESORNO_NO);
                if (StringUtils.isBlank(lpyfjdygx.getWjgs()) || StringUtils.isBlank(lpyfjdygx.getFjdz()) || lpyfjdygx.getFjdx() == null || StringUtils.isBlank(lpyfjdygx.getLjm())
                        || lpyfjdygx.getSx() == null) {
                    errorBean = new ErrorBean();
                    errorBean.setErrorData(ValidatorConstants.E1011);
                    errCodeList.add(errorBean);
                    break;
                }
            }
        }
        logger.info("--------------礼品详细介绍校验--------------");
        /* if (StringUtils.isBlank(paramLpxx.getLpxxjs())) {
             errorBean = new ErrorBean();
             errorBean.setErrorCode(ValidatorConstants.E1009);
             errCodeList.add(errorBean);
         }*/

        if (CollectionUtils.isNotEmpty(errCodeList)) {
            return errCodeList;
        }

        logger.info("--图文混排操作");
        if (StringUtils.isNotBlank(paramLpxx.getLpxxjs())) {
            ResultJson resultJson = this.saveTxtToDFS(appConfig.getDfsUploadUrl(), paramLpxx.getLpxxjs());
            if (resultJson.isResult()) {
                FileBean fb = (FileBean) resultJson.getObject();
                if (fb != null) {
                    TYyxtLpglLpyfjdygx lpyfjdygx = new TYyxtLpglLpyfjdygx();
                    lpyfjdygx.setLjm(fb.getFileName());
                    lpyfjdygx.setWjgs(fb.getFileExtName());
                    lpyfjdygx.setFjdx("".equals(fb.getFileSize()) ? 0 : Integer.parseInt(fb.getFileSize()));
                    lpyfjdygx.setFjdz(fb.getFilePath());
                    lpyfjdygx.setFjfl(CodeConstants.FJFL_LPXQ);
                    lpyfjdygx.setSfxyzh(CodeConstants.YESORNO_NO);
                    lpyfjdygx.setYwy(paramLpxx.getYwy());
                    lpsltList.add(lpyfjdygx);
                }
            } else {
                errorBean = new ErrorBean();
                errorBean.setErrorData(ValidatorConstants.E1010);
                errCodeList.add(errorBean);
                return errCodeList;
            }
        }

        lpsltList.add(logo);
        return null;
    }

    /**
     * getLpxxByLpid,根据礼品ID获取礼品信息. <br/>
     * Author: huangqq <br/>
     * Create Date: 2016年11月15日 <br/>
     * ===============================================================<br/>
     * Modifier: huangqq <br/>
     * Modify Date: 2016年11月15日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param lpid 礼品ID
     * @param ywy 业务域
     * @return 礼品信息
     * @since JDK 1.7
     */
    @Override
    public ViewLpxx getLpxxByLpid(String lpid, String ywy) {

        logger.info("根据礼品ID : " + lpid + ",获取礼品信息开始");

        ViewLpxx viewLpxx = tYyxtLpglLpxxMapper.getLpxxByid(lpid, ywy);

        if (viewLpxx != null) {
            logger.info("根据礼品ID获取礼品logo-缩略图-详细介绍");
            List<TYyxtLpglLpyfjdygx> lpyfjdygxList = lpyfjdygxMapper.getLpyfjdygxBylpid(lpid, ywy);
            if (CollectionUtils.isNotEmpty(lpyfjdygxList)) {
                Iterator<TYyxtLpglLpyfjdygx> its = lpyfjdygxList.iterator();
                while (its.hasNext()) {
                    TYyxtLpglLpyfjdygx lpyfjdygx = its.next();
                    if (CodeConstants.FJFL_LPLOGO.equals(lpyfjdygx.getFjfl())) {
                        viewLpxx.setLpLogo(lpyfjdygx);
                        its.remove();
                    }
                    if (CodeConstants.FJFL_LPXQ.equals(lpyfjdygx.getFjfl())) {
                        ResultJson res = this.readTxtFromDFS(appConfig.getDfsHost() + "/" + lpyfjdygx.getFjdz());
                        if (res.isResult()) {
                            viewLpxx.setLpxxjs(res.getObject().toString());
                        }
                        its.remove();
                    }
                }
                viewLpxx.setLpsltList(lpyfjdygxList);
            }
            logger.info("根据礼品ID : " + lpid + ",获取礼品信息结束");
            return viewLpxx;
        }
        return null;
    }

    /**
     * getLpxxList,查询礼品信息List. <br/>
     * Author: huangqq <br/>
     * Create Date: 2016年11月15日 <br/>
     * ===============================================================<br/>
     * Modifier: huangqq <br/>
     * Modify Date: 2016年11月15日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param paramLpcx 礼品信息查询传参
     * @return 礼品分页信息
     * @since JDK 1.7
     */
    @Override
    public Page getLpxxList(ParamLpcx paramLpcx) {
        logger.info("获取礼品信息List开始");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Page page = new Page();
        page.setCurrPage(paramLpcx.getCurrPage());
        page.setPageSize(paramLpcx.getPageSize());
        if (paramLpcx.getSjsjks() != null) {
            SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
            String sjsjksStr = fm.format(paramLpcx.getSjsjks());
            try {
                Date sjsjks = sdf.parse(sjsjksStr);
                paramLpcx.setSjsjks(sjsjks);
            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }
        }
        if (paramLpcx.getSjsjjs() != null) {
            SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
            String sjsjjsStr = fm.format(paramLpcx.getSjsjjs());
            try {
                Date sjsjjs = sdf.parse(sjsjjsStr);
                paramLpcx.setSjsjjs(sjsjjs);
            } catch (java.text.ParseException e) {

                e.printStackTrace();
            }
        }
        page.setParam(paramLpcx);
        int count = tYyxtLpglLpxxMapper.countLpxxListPagination(page);
        page.setTotal(count);
        logger.info("总条数：" + count);
        List<ViewLpcx> lpxxList = new ArrayList<ViewLpcx>();
        if (count > 0) {
            lpxxList = tYyxtLpglLpxxMapper.getLpxxListPagination(page);
            page.setData(lpxxList);
        }
        return page;
    }

    /**
     * updateLpxxZt,礼品上下架. <br/>
     * Author: huangqq <br/>
     * Create Date: 2016年11月15日 <br/>
     * ===============================================================<br/>
     * Modifier: huangqq <br/>
     * Modify Date: 2016年11月15日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param paramLpxxZt 礼品上下架信息
     * @param zh 账号
     * @return 执行结果
     * @since JDK 1.7
     */
    @Override
    public ResultJson updateLpxxZt(ParamLpxxZt paramLpxxZt, String zh) {
        ResultJson resultJson = new ResultJson(false);

        String[] ids = paramLpxxZt.getIds();
        if (ids.length <= 0) {
            resultJson.setMessage(ValidatorConstants.E1000);
            logger.info("-----------------操作结束-----------------");
            return resultJson;
        }
        TYyxtLpglLpxx lpxx = null;
        String ywy = paramLpxxZt.getYwy();
        int count = 0;
        for (String id : ids) {
            lpxx = new TYyxtLpglLpxx();
            lpxx.setOperatercode(zh);
            lpxx.setOperatetime(new Date());
            lpxx.setDelflag(CommonConstants.DELFLAG_UPDATE);
            lpxx.setVersions(this.getVersion());
            lpxx.setZkzt(paramLpxxZt.getLpzt());
            if (CodeConstants.ZKZT_SJ.equals(paramLpxxZt.getLpzt())) {
                lpxx.setSjsj(new Date());
            }
            lpxx.setId(id);
            lpxx.setYwy(ywy);
            tYyxtLpglLpxxMapper.updateLpZkzt(lpxx);
            count++;
        }
        if (count > 0) {
            resultJson.setResult(true);
        }
        return resultJson;
    }

    /**
     * validateLpmc,校验礼品名称唯一性. <br/>
     * Author: huangqq <br/>
     * Create Date: 2016年11月18日 <br/>
     * ===============================================================<br/>
     * Modifier: huangqq <br/>
     * Modify Date: 2016年11月18日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param paramLpxx 礼品名称参数
     * @return 校验结果
     * @since JDK 1.7
     */
    @Override
    public ResultJson validateLpmc(ParamLpxx paramLpxx) {
        ResultJson rs = new ResultJson(true);
        if (paramLpxx != null && StringUtils.isNotBlank(paramLpxx.getLpmc())) {
            List<ViewLpxx> list = tYyxtLpglLpxxMapper.getLpxxBylpmc(paramLpxx.getLpmc().trim(), paramLpxx.getYwy());
            if (CollectionUtils.isNotEmpty(list)) {
                if (StringUtils.isNotBlank(paramLpxx.getId())) { //编辑
                    ViewLpxx lpxx = list.get(0);
                    if (!lpxx.getId().equals(paramLpxx.getId().trim())) {
                        rs.setResult(false);
                        rs.setMessage(ValidatorConstants.E1012);
                    }
                } else { //新增
                    rs.setResult(false);
                    rs.setMessage(ValidatorConstants.E1012);
                }
            }
        }
        return rs;
    }

}
